package form

import (
	"gitee.com/zjlsliupei/ghelp"
	"gitee.com/zjlsliupei/ndb/config"
	"gitee.com/zjlsliupei/ndb/request"
	"github.com/gin-gonic/gin"
	"github.com/tidwall/gjson"
)

type List struct {
	option     config.Option
	rpcName    string
	funcName   string
	arg        ghelp.MAP
	meta       ghelp.MAP
	ginContext *gin.Context
}

func NewList(option config.Option, rpcName string) List {
	return List{
		option:   option,
		rpcName:  rpcName,
		funcName: "List",
		arg:      make(ghelp.MAP),
	}
}

// SetGroupId 不超过20位，用于数据分组
func (this *List) SetGroupId(groupId string) *List {
	this.arg["group_id"] = groupId
	return this
}

// SetFormId 需要获取的表单id, 必填
func (this *List) SetFormId(formId string) *List {
	this.arg["form_id"] = formId
	return this
}

// SetSize 默认15
func (this *List) SetSize(size int64) *List {
	this.arg["size"] = size
	return this
}

// SetPage 从1开始
func (this *List) SetPage(page string) *List {
	this.arg["page"] = page
	return this
}

// SetWhere 筛选条件，每个条件之间是and关系。[in]：匹配查询（or），[notin]：不匹配；[range]：区间查询，数字或者日期，null表示不限制，比如[1,null]表示大于等于1的区间，[like]：模糊查询，用于txt文本类型的字段；
func (this *List) SetWhere(where []interface{}) *List {
	this.arg["where"] = where
	return this
}

// SetFields 返回部分字段
func (this *List) SetFields(fields []string) *List {
	this.arg["fields"] = fields
	return this
}

// SetSort 排序
func (this *List) SetSort(sort []interface{}) *List {
	this.arg["sort"] = sort
	return this
}

// SetCalc 要统计的字段，只支持数字类型。加了该参数后，将不返回具体的数据，只返回该字段的合计、最大值、最小值、平均数、条数
func (this *List) SetCalc(calc string) *List {
	this.arg["calc"] = calc
	return this
}

// AutoMeta 自动设置meta，根据gin的上下文来解析，meta; 如果同时使用了Meta优先以Meta为准
func (this *List) AutoMeta(c *gin.Context) *List {
	_c := c.Copy()
	this.ginContext = _c
	return this
}

// SetMeta 设置meta
func (this *List) SetMeta(meta ghelp.MAP) *List {
	this.meta = meta
	return this
}

func (this *List) Do() (gjson.Result, error) {
	req := request.NewRequest(this.option.Addr)
	req.FuncName(this.funcName)
	req.RpcName(this.rpcName)
	req.AutoMeta(this.ginContext)
	req.SetMeta(this.meta)
	return req.Do(this.arg)
}
